package com.zengqingfa.imp.demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.zengqingfa.imp.demo.dao.EmpDao;
import com.zengqingfa.imp.demo.dto.Emp;
import com.zengqingfa.imp.demo.dto.EmpExportDTO;
import com.zengqingfa.imp.demo.dto.EmpQueryDTO;
import com.zengqingfa.imp.demo.service.EmpService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @fileName: EmpServiceImpl
 * @author: zengqf3
 * @date: 2021-3-3 13:34
 * @description:
 */
@Service
@Slf4j
public class EmpServiceImpl implements EmpService {


    @Resource
    private EmpDao empDao;

    @Override
    public List<Emp> findAll() {
        log.error("start....");
        long start = System.currentTimeMillis();
        Integer count = empDao.findCount();
        List<Emp> list = empDao.findAll();
        log.error("查询全部消耗了:" + (System.currentTimeMillis() - start) + "ms");
        log.error("end....");
        return list;
    }

    @Override
    public List<Emp> findAll2() {
        log.error("start....");
        long start = System.currentTimeMillis();
        List<Emp> empListVos = new ArrayList<>();
        try {
            Integer total = empDao.findCount();
            int threadSize = total / 1000;//每页大小
            int threadNum = total % threadSize == 0 ? total / threadSize : total / threadSize + 1;//总页数
            ExecutorService exec = Executors.newFixedThreadPool(threadNum);  //threadNum线程数
            List<Callable<Integer>> tasks = new ArrayList<>();
            Callable<Integer> task = null;
            Map<Integer, List<Emp>> map = new HashMap();
            for (int i = 1; i <= threadNum; i++) {
                final int pageNum = i;
                task = new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        List<Emp> partyOrgPersonVoList = findByPage(pageNum, threadSize);
                        map.put(pageNum, partyOrgPersonVoList);
                        return 1;
                    }
                };
                tasks.add(task);
            }
            exec.invokeAll(tasks);
            if (CollUtil.isNotEmpty(map)) {
                for (int i = 1; i <= threadNum; i++) {
                    List<Emp> empVos = map.get(i);
                    empListVos.addAll(empVos);
                    map.remove(i);
                }
            }
            exec.shutdown();
            log.error("【批量查询人员信息】线程任务执行结束,执行任务消耗了 ：" + (System.currentTimeMillis() - start) + "毫秒");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return empListVos;
    }


    @Override
    public Emp findById(Integer id) {
        return empDao.findById(id);
    }

    @Override
    public Integer findCount() {
        return empDao.findCount();
    }

    @Override
    public List<Emp> findByPage(Integer pageNo, Integer pageSize) {
        Integer offset = (pageNo - 1) * pageSize;
        return empDao.findByPage(offset, pageSize);
    }

    @SneakyThrows
    @Override
    public void export(HttpServletResponse response, EmpQueryDTO dto) {
        // 设置防止中文名乱码
        String filename = URLEncoder.encode("员工信息", "utf-8");
        // 文件下载方式
        response.setHeader("Content-disposition", "attachment;filename="+filename + ".xlsx");
        //查询数据
        List<EmpExportDTO> list = empDao.list(dto);
        // 写入数据到excel
        EasyExcel.write(response.getOutputStream(), EmpExportDTO.class)
                .sheet("用户信息")
                .doWrite(list);
    }
}
